//
//  BaseTabBarViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/14.
//

import UIKit

class BaseTabBarViewController: UITabBarController,UITabBarControllerDelegate {
    
    
    var homeVC:BaseNavigationController!
    var meVc:BaseNavigationController!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        
        if #available(iOS 13.0, *) {
            self.tabBar.backgroundImage = UIImage.imageFromColor(color: Colors.navigationColor)
        } else {
            self.tabBar.backgroundImage = UIImage.imageFromColor(color: .white)
        }
    }
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
        if UserDefaultTools.getToken() == nil && viewController == tabBarController.viewControllers![1] {
           
            let vc = LoginViewController()
            vc.title = "登陆"
            let loginVC = BaseNavigationController(rootViewController: vc)
            loginVC.modalPresentationStyle = .fullScreen
            if #available(iOS 13.0, *) {
                loginVC.isModalInPresentation = true
            }
            self.present(loginVC, animated: true, completion: nil)
            
            return false
        }
        
        return true
    }
}

extension BaseTabBarViewController {
    
    func setupUI() -> Void {
        
        self.delegate = self
        
        self.tabBar.isTranslucent = false
        if #available(iOS 13.0, *) {
            self.tabBar.backgroundImage = UIImage.imageFromColor(color: Colors.navigationColor)
        } else {
            self.tabBar.backgroundImage = UIImage.imageFromColor(color: .white)
        }

        let home = MainViewController(titles:  ["推荐项目","热门项目","最近更新"], tableHeaderH: 0)
        home.title = "发现"
        home.tabBarItem.image = UIImage(named: "discover")
        let imgSel = UIImage(named: "discover_selected")?.withRenderingMode(.alwaysOriginal)
        home.tabBarItem.selectedImage = imgSel
        homeVC = BaseNavigationController(rootViewController: home)
        
        let me = MeViewController(model: UserDefaultTools.getUser(), titles: ["动态","项目","Star","Watch"], tableHeaderH: 140)
        me.title = "我的"
        me.tabBarItem.image = UIImage(named: "mine")
        me.tabBarItem.selectedImage = UIImage(named: "mine_selected")?.withRenderingMode(.alwaysOriginal)
        meVc = BaseNavigationController(rootViewController: me)
        
        tabBar.tintColor = Colors.BLUE_COLOR
        
        viewControllers = [homeVC, meVc]
        
    }
}

